<template>
	<section>
		<div>
			<!--工具条-->
			<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
				<!--
            :inline="true":行内form表单
            :model="searchForm"  双向绑定的公共前缀
            -->
				<el-form :inline="true" :model="searchForm">
					<el-form-item>
						<el-input v-model="searchForm.name" placeholder="姓名"></el-input>
					</el-form-item>
					<el-form-item>
						<el-select v-model="searchForm.state" clearable  placeholder="请选择状态">
							<el-option label="启用" value="0"></el-option>
							<el-option label="禁用" value="-1"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" v-on:click="getDepartment">查询</el-button>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="handleAdd">新增</el-button>
					</el-form-item>
				</el-form>
			</el-col>

			<!--列表-->
			<el-table :data="department" style="width: 100%;" @selection-change="selsChange">
				<el-table-column type="selection" width="55">
				</el-table-column>
				<el-table-column type="index" width="60">
				</el-table-column>
				<el-table-column prop="name" label="部门名称">
				</el-table-column>
				<el-table-column prop="sn" label="部门编号">
				</el-table-column>
				<el-table-column prop="state" label="启用状态" :formatter="formatState">
				</el-table-column>
				<el-table-column prop="manager.username" label="部门经理">
				</el-table-column>
				<el-table-column prop="parent.name" label="上级部门">
				</el-table-column>
				<el-table-column label="操作">
					<template scope="scope">
						<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
						<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!--工具条-->
			<el-col :span="24" class="toolbar">
				<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
				<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
				</el-pagination>
			</el-col>

			<!--新增/修改界面-->
			<el-dialog :title="title" :visible.sync="addFormVisible" :close-on-click-modal="false">
				<el-form :model="addForm" label-width="80px" :rules="formRules" ref="addForm">
					<el-form-item label="姓名" prop="name">
						<el-input v-model="addForm.name" auto-complete="off"></el-input>
					</el-form-item>
					<el-form-item label="部门编号" prop="sn">
						<el-input v-model="addForm.sn" auto-complete="off"></el-input>
					</el-form-item>
					<el-form-item label="启用状态">
						<el-radio-group v-model="addForm.state">
							<el-radio class="radio" :label="0">启用</el-radio>
							<el-radio class="radio" :label="-1">禁用</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="部门经理" prop="managerId">
						<el-select v-model="addForm.managerId"  clearable placeholder="请选择">
							<el-option
									v-for="item in managers"
									:key="item.id"
									:label="item.username"
									:value="item.id">
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="上级部门">
						<el-cascader  v-model="addForm.path"
									  :options="parentDepartments"
									  :props="{ checkStrictly: true }"
									  clearable></el-cascader>
					</el-form-item>
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button @click.native="addFormVisible = false">取消</el-button>
					<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
				</div>
			</el-dialog>
		</div>
	</section>
</template>

<script>
    export default {
        data() {
            return {
                //模态框标题
                title:'',
                //上级所有的部门
                parentDepartments:[],
                //查询框默认值
                searchForm: {
                    name: '',
					state:''
                },
                //列表选中列
                sels: [],
                //部门数据
                department: [],
				//默认总条数
				total:0,
				//当前页
                currentPage:1,
				//当前页条数
                pageSize:10,
				//删除提示框
                listLoading: false,
				//默认弹出框状态，新增界面是否显示
                addFormVisible: false,
				//加载中
                addLoading: false,
				//校验规则
                formRules: {
                    name: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ],
                    sn: [
                        { required: true, message: '请输入部门编号', trigger: 'blur' }
                    ],
                    managerId: [
                        { required: true, message: '请选择部门经理', trigger: 'change' }
                    ],
                },
                //新增界面数据
                addForm: {
                    id:'',
                    name: '',
                    sn: '',
                    state: 0,
                    managerId:'',
                    parent:'',
                    //层级
                    path:""
                },
				//查询所有的部门经理
                managers:[],
                //部门列表
                departments:[],
            }
        },
        methods: {
            //点击添加按钮弹出窗体
            handleAdd(){
                //修改标题
				this.title="新增";
                //先重置
                if(this.$refs["addForm"]){
                    //当出现了校验规则的时候，才能进行重置
                    this.$refs["addForm"].resetFields();//this.$refs.ruleForm.resetFields()
                }
                //手动清空form表单
                for(var k in this.addForm){
                    this.addForm[k] = "";
                }
                this.addForm.state = 0;
                //弹出窗体
                this.addFormVisible = true;
			},
            //高级查询
            getDepartment(){
                this.currentPage=1;
                this.loadDepartments();
			},
            //选中数据的变化
            selsChange: function (sels) {
                this.sels = sels;
            },
            //启用状态
            formatState: function (row, column) {
                return row.state == 0 ? '启用':'禁用';
            },
            //给编辑按钮注册事件
            handleEdit(index, row) {
                this.title="修改";
                //回显数据,能回显示大部分数据
                for(var i in this.addForm){
                    this.addForm[i] = row[i];
                }
                //给managerId赋值
				this.addForm.managerId=row.manager.id;
				//path应改为数组
				//在设计数据库的时候，path可能为null，如果path为null，将其改为空字符串
				if(this.addForm.path==null){
				    this.addForm.path="";
				}
				this.addForm.path=this.addForm.path.split(",");
                this.addFormVisible=true;
            },
			//给删除按钮注册事件
            handleDel(index,row){
                this.$confirm('您确认离我而去吗?', '提示', {
                    type: 'warning'
                }).then(() => {
					this.$http.delete("/department/"+row.id).then(res=>{
                        let {success, msg} = res.data;
                        if(success) {
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            //刷新界面
                            this.loadDepartments();
                        }else {
                            this.$message.error('错了哦，这是一条错误消息');
						};
					})
				}).then(res=>{

				});
			},
			//查询部门列表
			loadDepartments(){
                let param = {"currentPage":this.currentPage,"pageSize":this.pageSize,
							"name":this.searchForm.name,"state":this.searchForm.state};
				this.$http.patch("/department",param).then(res=>{
				    this.department=res.data.list;
				    this.total=res.data.total;
				}).catch(res=>{

				});
			},
			//当前页变化执行函数
            handleCurrentChange(val){
                this.currentPage=val;
				this.loadDepartments();
			},
            //批量删除
            batchRemove: function () {
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
					this.$http.patch("/department/batchRemove",this.sels).then(res=>{
					    let {success,msg} = res.data;
					    if(success){
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            //刷新页面
							this.loadDepartments();
						}else {
                            this.$message.error('错了哦，这是一条错误消息');
						};
					});
                }).catch(() => {

                });
            },
			//添加/修改提交按钮事件
            addSubmit(){
                //手动创建一个manager
				let manager = {"id": this.addForm.managerId};
				//手动给addForm添加属性
				this.addForm.manager=manager;
				//手动获取path
                let path = this.addForm.path;
				let parent = {"id":path[path.length-1]};
				this.addForm.parent=parent;
                this.addForm.path=path.toString();
                //提交form表单之前必须要进行校验
                this.$refs["addForm"].validate((valid) => {
                    //校验通过之后，执行if语句中的内容
                    if (valid) {
                        this.$http.post("/department", this.addForm).then(res => {
                            let {success, msg} = res.data;
                            if(success){
                                //关闭模态框
                                this.addFormVisible = false;
                                //刷新界面
                                this.loadDepartments();
                                //刷新上级部门
                                this.loadParentDepartments();
                            }else{
                                this.$message.error(msg);
                            }
                        });
                    }
                });
			},
			//查询所有的部门经理
			findManager(){
                this.$http.patch("/department/findManager").then(res=>{
					this.managers=res.data;
				})
			},
			//查询部门树
            loadParentDepartments(){
                this.$http.patch("/department/findDepartmentTree").then(res=>{
                    this.parentDepartments=res.data;
				})
			}
        },
		mounted(){
            //加载分页数据
            this.loadDepartments();
            //查询部门经理
			this.findManager();
			//查询部门树
			this.loadParentDepartments();
		}
    }
</script>